\insert 'List.oz'
\insert 'Visualizer.oz'

%%
%% Task 6
%%

declare FewerFind FewerFindMain FewerFindTop FewerFindBottom
fun {FewerFind Main Top Bottom Future}
   local NewMain NewTop NewBottom NewFuture NewTop Flytt in
      case Future of StartVogn|_ then
	 if {Member Main StartVogn} then
	    Flytt#NewMain#NewTop#NewBottom = {FewerFindMain Main Top Bottom StartVogn}
	 elseif {Member Top StartVogn} then
	    Flytt#NewMain#NewTop#NewBottom = {FewerFindTop Main Top Bottom StartVogn}
	 else
	    Flytt#NewMain#NewTop#NewBottom = {FewerFindBottom Main Top Bottom StartVogn}
	 end
	 NewFuture = {Drop Future 1}
	 {Append Flytt {FewerFind NewMain NewTop NewBottom NewFuture}}
      else
	 nil
      end
   end
end

fun {FewerFindMain Main Top Bottom StartVogn}
   local Foran Bak Flytt Na Nb in
      Foran#Bak = {SplitTrain Main StartVogn}
      Na  = {Length Foran} 
      Nb = {Length Bak} + 1

      Flytt = trackA(Nb)|trackB(Na)|trackA(~1)|nil
      Flytt#StartVogn#Bak#Foran
   end
      
end

fun {FewerFindTop Main Top Bottom StartVogn}
   local Foran Bak Na NewFuture NewBottom Flytt in
      Foran#Bak = {SplitTrain Top StartVogn}

      Na = {Length Foran}

      Flytt = trackA(~Na)|trackB(Na)|trackA(~1)|nil
      NewBottom = {Append Foran Bottom }
      
      Flytt#StartVogn#Bak#NewBottom
   end   
end


fun {FewerFindBottom Main Top Bottom StartVogn}
   local Foran Bak NewFuture Flytt Na NewTop in
      Foran#Bak = {SplitTrain Bottom StartVogn}

      Na = {Length Foran}

      Flytt = trackB(~Na)|trackA(Na)|trackB(~1)|nil
      NewTop = {Append Foran Top}
      
      Flytt#StartVogn#NewTop#Bak
   end
end

fun {SplitTrain VognListe Vogn}
   local Pos Hs Ts in
      Pos = {Position VognListe Vogn}
      Hs = {Take VognListe (Pos - 1)}
      Ts = {Drop VognListe Pos}
      Hs#Ts
   end
end
